package com.qianclass.talklive.app.activity;


import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.qianclass.talklive.R;
import com.qianclass.talklive.app.bean.TestGroupLoginBean;
import com.qianclass.talklive.app.utils.Constant;
import com.qianclass.talklive.app.utils.DateTime;
import com.qianclass.talklive.app.utils.DoCallback;
import com.qianclass.talklive.app.utils.FileLogUtils;
import com.qianclass.talklive.app.utils.Info;
import com.qianclass.talklive.app.utils.InfoAccessImpl;
import com.qianclass.talklive.app.utils.LogUtil;
import com.qianclass.talklive.app.utils.StringEncrypt;
import com.qianclass.talklive.app.utils.ThreadUtils;
import com.qianclass.talklive.app.utils.ToastUtils;
import com.qianclass.talklive.app.utils.VerificationKeyUtils;
import com.qianclass.talklive.app.utils.ZipUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;


/**
 * Created by apple on 15/9/15.
 */
public class MainActivity extends BaseActivity {
	private static final String TAG ="MainActivity" ;
	private static final int REQUEST_WRITE = 0;
	public static final int TYPE_SHOW_UPDATE_DIALOG = 0;
	public static final int TYPE_SHOW_ERROR = 1;
	private String versionName;
	private String mUrl;
	private static final int REQUEST_INSTALL_CODE = 100;
	private static final int SERVERIP = 101;
	private File apkFile;
	private InputStream is ;
	private FileOutputStream os ;
	private int layoutID;
	private DateFormat format = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
	String userInfoName;
	private String VerificationKey;
	private int userID;
	private String  username,pwd,userName;
	private String LOGIN_MECHANISM_ID = Info.MECHANISM_ID;
	private String replaceUpdateContent;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
				case TYPE_SHOW_UPDATE_DIALOG:
					showUpdateDialog();
					break;
				case SERVERIP:
					Log.i("chengwneqiang","mHandler");
					String countryCode = (String) msg.obj;
					if (countryCode.equals("CN")) {
						Constant.setBaseDynamicIp(Constant.BASE_ZH_IP);
					} else {
						Constant.setBaseDynamicIp(Constant.BASE_EN_IP);
					}

					processEnter();
					break;

				default:
					break;
			}
		};
	};
	private int mVersonCode;
	private int mLocalVersonCode;
	private ProgressDialog mProgressDialog;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		super.requestWindowFeature(Window.FEATURE_NO_TITLE);
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

		layoutID = R.layout.activity_splash;

		setContentView(layoutID);

		EventBus.getDefault().register(this);

		EventBus.getDefault().post("app_init");

	}

	@Override
	protected void onResume()
	{
		super.onResume();
		InfoAccessImpl.getInstance(this);
	}

	@Subscribe(threadMode = ThreadMode.MAIN)
	public void onPocess(String msg){
		if (msg.equals("init_finished")) {

			getDocServer();
		}
	}

	private boolean isZhEnvironment() {
		Locale locale = getResources().getConfiguration().locale;
		String language = locale.getLanguage();
		String country = locale.getCountry();
		LogUtil.i("local_language", language);
		FileLogUtils.write("Device Country: " + country + "/Language:" + language);
		if (language.endsWith("zh"))
			return true;
		else
			return false;
	}

	private void getDocServer() {

		if (isZhEnvironment()) {
			Constant.setLocalDynamicIp(Constant.BASE_ZH_IP);
		} else {
			Constant.setLocalDynamicIp(Constant.BASE_EN_IP);
		}

		HttpUtils httpUtils = new HttpUtils();

		LogUtil.e("ip", Constant.getLocalDynamicIp());
		LogUtil.e("ip", Constant.getGetDocserverUrl());
		RequestParams params = new RequestParams();

		VerificationKeyUtils keyUtils = new VerificationKeyUtils();
		String verificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);

		params.addBodyParameter("Version", Info.APIVERSION);
		params.addBodyParameter("UA", "Android");
		params.addBodyParameter("VerificationKey", verificationKey);

		FileLogUtils.write("getDocServerURL:" + Constant.getGetDocserverUrl());
		httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getGetDocserverUrl(), params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				try {
					FileLogUtils.write("getDocServer:" + responseInfo.result);
					JSONObject docJsonObject = new JSONObject(responseInfo.result);
					String ip = docJsonObject.getString("FileTransfer");
					String countryCode = docJsonObject.getString("CountryCode");

					Message obtain = Message.obtain();
					obtain.obj = countryCode;
					obtain.what = SERVERIP;
					mHandler.sendMessage(obtain);

				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException e, String s) {
				e.printStackTrace();
				Toast.makeText(MainActivity.this, s, Toast.LENGTH_SHORT).show();
				processEnter();
			}
		});
	}

	public void processEnter() {
		//获取用户名称，用于Log命名
		LogUtil.i("isfirst", "isfirst ||" + ((TalkApplication) getApplication()).getIsFirst());
		if(((TalkApplication)getApplication()).getIsFirst()==false) {
			userInfoName = (((TalkApplication) getApplication()).getUSerAccount());
			userID = ((TalkApplication) getApplication()).getUserID();

			Log.i("chengwenqiang","-------------processEnter");
			logUpload();
		}

		Log.i("chengwenqiang","----------------initData");
		initData();

		/**版本更新检测**/
		Log.i("chengwenqiang","----------------CheckVersionTask");
		new Thread(new CheckVersionTask()).start();
	}

	private void logUpload() {

		/***
		 * POST 请求方式
		 参数：
		 Version：字符串，接口的版本号，与本文档版本一致。
		 UA：字符串，客户端类型。iOS/Android/Windows/MacOS。
		 Source：字符串，来源。Windows/iOS/Android/MacOS。
		 GroupID：字符串，机构标识，没有可不填。
		 UserID：字符串，用户标识，可填用户账号/ID。
		 RoomID：字符串，教室 ID，如果未进入教室，可以不填。
		 FileName：字符串，日志文件名。
		 VerificationKey：密文。机构+时间字符串（例如：”rQ2ym
		 3Jfk3K+2016-11-01 08:30:00” ）。字符串使用 s-1 算法加密。
		 FileStream 文件流。
		 */

		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		String time = format.format(new Date());
		String preCrashStr;

		if (Info.MECHANISM_ID.equals(Info.TestGroupAgencyID)) {
			preCrashStr = "-testgroup";
		} else if (Info.MECHANISM_ID.equals(Info.TracyClassAgencyID)) {
			preCrashStr = "-tracy";
		} else if (Info.MECHANISM_ID.equals(Info.TutorAgencyID)) {
			preCrashStr = "-tutor";
		}  else if (Info.MECHANISM_ID.equals(Info.EClassAgencyID)) {
			preCrashStr = "-eclass";
		} else if (Info.MECHANISM_ID.equals(Info.PublicAgencyID)) {
			preCrashStr = "-public";
		} else if (Info.MECHANISM_ID.equals(Info.TalkillaAgencyID)) {
			preCrashStr = "-talkilla";
		} else if (Info.MECHANISM_ID.equals(Info.FeiboAgencyID)) {
			preCrashStr = "-feibo";
		} else if (Info.MECHANISM_ID.equals(Info.SeekeryardAgencyID)) {
			preCrashStr = "-seekeryard";
		}else {
			preCrashStr = "-public";
		}

		String appName = getResources().getString(R.string.app_name);
		String fileName = "crash-" + appName + ".log";
		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/EclassCrash/";
		String newFileName = time + preCrashStr + "-Crash-" + userInfoName + "-" + userID + ".log";
		String destDirPath;
		// 判断是否有SD卡或者外部存储器
		if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
			destDirPath = getExternalFilesDir("Log").getPath() + "/";
		} else {
			destDirPath = getFilesDir().getPath() + "/Log/";
		}

		File srcFile = new File(path + fileName);
		if (srcFile.exists() && srcFile.isFile()) {
			File destDir = new File(destDirPath);
			if (!destDir.exists()) {
				destDir.mkdirs();
			} else {
				srcFile.renameTo(new File(destDirPath + File.separator + newFileName));
			}
		}

		File logDir = new File(destDirPath);
		if (logDir.exists()) {
			try {
				String zipFileName = time + preCrashStr + "-" + userInfoName + "-" + userID + ".zip";
				final String zipFilePath = getExternalFilesDir(null) + zipFileName;

				ZipUtil.zipFolder(destDirPath, zipFilePath);
				for (File logFile : logDir.listFiles()) {
					if (logFile.isFile()){
						logFile.delete();
					}
				}
				logDir.delete();

				final File logZipFile = new File(zipFilePath);

				VerificationKeyUtils keyUtils = new VerificationKeyUtils();
				VerificationKey = keyUtils.getVerificationKey(Info.MECHANISM_ID);

				params.addBodyParameter("Version", Info.APIVERSION);
				params.addBodyParameter("UA", "Android");
				params.addBodyParameter("Source", "Android");
				params.addBodyParameter("GroupID", Info.MECHANISM_ID);
				params.addBodyParameter("UserID", userInfoName);
				params.addBodyParameter("VerificationKey", VerificationKey);

				params.addBodyParameter("FileStream", logZipFile);

				params.addBodyParameter("FileName", zipFileName);

				FileLogUtils.write("CrashLogUpload:" + Constant.getLogUploadUrl());
				httpUtils.send(HttpRequest.HttpMethod.POST,
							   Constant.getLogUploadUrl(),
							   params,
							   new RequestCallBack<String>() {

								   @Override
								   public void onSuccess(ResponseInfo<String> responseInfo) {

									   LogUtil.i(TAG, responseInfo.result);
									   try {
										   JSONObject json = new JSONObject(responseInfo.result);
										   String result = json.getString("Result");

										   if ("true".equals(result)) {//上传成功
											   LogUtil.i(TAG, "上传崩溃日志成功");

											   logZipFile.delete();
										   }

									   } catch (JSONException e) {
										   e.printStackTrace();
									   }

								   }

								   @Override
								   public void onFailure(HttpException e, String s) {
								   }
							   });

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private class CheckVersionTask implements Runnable {

		@Override
		public void run() {
			// 去服务器获得最新的版本信息
			DateTime dateTime = new DateTime();
			String time = dateTime.getDateTime();

			String VerificationKey = StringEncrypt.S1Encrypt(Info.MECHANISM_ID + "+" + time, Info.API_EncryptionKey);

			HttpUtils httpUtils = new HttpUtils();
			RequestParams params = new RequestParams();

			params.addBodyParameter("Version",Info.APIVERSION);
			params.addBodyParameter("UA","Android");
			params.addBodyParameter("VerificationKey",VerificationKey);
			FileLogUtils.write("VersionUpdate:" + Constant.getCheckClientVersion());
			httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getCheckClientVersion(), params, new RequestCallBack<String>() {
				@Override
				public void onSuccess(ResponseInfo<String> responseInfo) {
					LogUtil.i(TAG,"--"+responseInfo.result);
					FileLogUtils.write("VersionUpdateResult:" + responseInfo.result);

					try {
						JSONObject jsonObject = new JSONObject(responseInfo.result);
						if(jsonObject.has("Result") && !jsonObject.getBoolean("Result"))
						{
							Log.i("MainActivity.java","no version to update");
							return;
						}
						String version = jsonObject.getString("Version");

						mUrl = jsonObject.getString("Url");

						String verStr = version.replaceAll("\\.", "");

						if (verStr != null) {
							mVersonCode = Integer.parseInt(verStr);
						}
						if (versionName != null) {
							String verLocalStr= versionName.replaceAll("\\.", "");
							mLocalVersonCode = Integer.parseInt(verLocalStr);
						}

						if(jsonObject.has("UpdateContent")){
							String UpdateContent = jsonObject.getString("UpdateContent");
							replaceUpdateContent = UpdateContent.replaceAll("\\\\n", "\r\n");

						}

						if(mLocalVersonCode<mVersonCode){
							LogUtil.i("Test","版本号"+version+"  和当前版本号  "+ versionName+"不一致，弹出更新对话框");
							Message message = Message.obtain();
							message.obj=TYPE_SHOW_UPDATE_DIALOG;
							mHandler.sendMessage(message);
						}else{
							dumpToSsoCourse();
//							Boolean autoLogin = ((TalkApplication) getApplication()).getAutoLogin();
//							Boolean autoLogin =true;

//							((TalkApplication) getApplication()).setUserAccount("showstudy01");
//							((TalkApplication) getApplication()).setUserPwd("123456");

//							if(!((TalkApplication) getApplication()).getUSerAccount().equals("")&&!((TalkApplication) getApplication()).getUserPwd().equals("")&&autoLogin==true){
//								username = ((TalkApplication) getApplication())
//										.getUSerAccount();
//								pwd = ((TalkApplication) getApplication())
//										.getUserPwd();
//								dumpToCourse();
//							}else {
//								goApp(1000);
//								LogUtil.i(TAG,"-------");
//							}
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

				@Override
				public void onFailure(HttpException e, String s) {
					LogUtil.i("Test","版本检测失败");
					Toast.makeText(MainActivity.this, "版本检测失败", Toast.LENGTH_SHORT).show();
					goApp(1000);
				}
			});
		}
	}

    //
	private void dumpToSsoCourse(){
		if (Info.MECHANISM_ID.equals(Info.PublicAgencyID)) {//通用
			LOGIN_MECHANISM_ID = Info.PublicAgencyID;
		} else if (Info.MECHANISM_ID.equals(Info.TestGroupAgencyID)) {//TestGroup
			LOGIN_MECHANISM_ID = Info.TestGroupAgencyID;
		} else if (Info.MECHANISM_ID.equals(Info.TracyClassAgencyID)) {//Tracy
			LOGIN_MECHANISM_ID = Info.TracyClassAgencyID;
		} else if (Info.MECHANISM_ID.equals(Info.TutorAgencyID)) {//Tracy
			LOGIN_MECHANISM_ID = Info.TutorAgencyID;
		} else if (Info.MECHANISM_ID.equals(Info.FeiboAgencyID)) {//Feibo
			LOGIN_MECHANISM_ID = Info.FeiboAgencyID;
		} else if (Info.MECHANISM_ID.equals(Info.SeekeryardAgencyID)) {//Seekeryard
			LOGIN_MECHANISM_ID = Info.SeekeryardAgencyID;
		}
		TalkApplication.setMechanismID(LOGIN_MECHANISM_ID);

		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("UA", "Android");
		params.addBodyParameter("Token", InfoAccessImpl.getInstance(this).getTokenId());
		params.addBodyParameter("UserAccount", InfoAccessImpl.getInstance(this).getHottvId());

		FileLogUtils.write("AutoLogin:" + Constant.getSsoLoginUrl());
		String url = Constant.getSsoLoginUrl();
		Log.i("chengwenqiang","url:"+url);
		Log.i("chengwenqiang","Token:"+InfoAccessImpl.getInstance(this).getTokenId());
		Log.i("chengwenqiang","UserAccount:"+InfoAccessImpl.getInstance(this).getHottvId());
		httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getSsoLoginUrl(), params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				LogUtil.i(TAG, "Login response " + responseInfo.result);
				try {
					JSONObject responseJson;
					responseJson = new JSONObject(responseInfo.result);

					if (responseJson.has("Result")) {

						String result = responseJson.getString("Result");
						if (result.equals("true")) {
							if (responseJson.has("Token")) {
								String token = responseJson.getString("Token");
								Gson gson = new Gson();
								TestGroupLoginBean testGroupLoginBean = gson.fromJson(responseInfo.result, TestGroupLoginBean.class);
								String userid = testGroupLoginBean.getUserID();
								String userName = testGroupLoginBean.getUserName();
								int userType = testGroupLoginBean.getUserType();
								String userAccount = testGroupLoginBean.getUserAccount();
								if(null!=userid) {
									((TalkApplication) getApplication()).setUserID(Integer.parseInt(userid));
								}
								Intent intent = new Intent(MainActivity.this, CourseInfoActivity.class);
								intent.putExtra("token", token);
								intent.putExtra("UserID", userid);
								intent.putExtra("UserType", userType);
								intent.putExtra("UserName", userName);
								intent.putExtra("AgencyID", LOGIN_MECHANISM_ID);
								intent.putExtra("UserAccount", userAccount);
								startActivity(intent);
								finish();
							}
						} else {
							ThreadUtils.runOnMainThread(new Runnable() {
								@Override
								public void run() {
									ToastUtils.showToast(MainActivity.this,getResources().getString(R.string.login_failed_and_check_info));
									goApp(1000);
								}
							});
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException e, final String s) {
				ThreadUtils.runOnMainThread(new Runnable() {
					@Override
					public void run() {
						LogUtil.e("loginfailed", s);
						ToastUtils.showToast(MainActivity.this, s);
						goApp(0);
					}
				});
			}
		});
	}

	private void dumpToCourse() {
		LogUtil.i(TAG,"已存账号密码，自动登录"+username+"---"+pwd);
		if (username.length() > 0) {

			String mStrUpCase = username.toUpperCase();

			if (mStrUpCase.startsWith("T_")) {

				userName = mStrUpCase.substring(2);
				LOGIN_MECHANISM_ID = Info.TAgencyID;

			} else if (mStrUpCase.startsWith("ECLASS_")) {
				userName = username;
				LOGIN_MECHANISM_ID = Info.EClassAgencyID;
			} else {
				// public testgroup  tracy
				if (Info.MECHANISM_ID.equals(Info.PublicAgencyID)) {//通用
					LOGIN_MECHANISM_ID = Info.PublicAgencyID;
				} else if (Info.MECHANISM_ID.equals(Info.TestGroupAgencyID)) {//TestGroup
					LOGIN_MECHANISM_ID = Info.TestGroupAgencyID;
				} else if (Info.MECHANISM_ID.equals(Info.TracyClassAgencyID)) {//Tracy
					LOGIN_MECHANISM_ID = Info.TracyClassAgencyID;
				} else if (Info.MECHANISM_ID.equals(Info.TutorAgencyID)) {//Tracy
					LOGIN_MECHANISM_ID = Info.TutorAgencyID;
				} else if (Info.MECHANISM_ID.equals(Info.FeiboAgencyID)) {//Feibo
					LOGIN_MECHANISM_ID = Info.FeiboAgencyID;
				} else if (Info.MECHANISM_ID.equals(Info.SeekeryardAgencyID)) {//Seekeryard
					LOGIN_MECHANISM_ID = Info.SeekeryardAgencyID;
				}
				TalkApplication.setMechanismID(LOGIN_MECHANISM_ID);
				userName = username;
			}
		}

		VerificationKeyUtils keyUtils = new VerificationKeyUtils();
		String VerificationKey = keyUtils.getVerificationKey(LOGIN_MECHANISM_ID);
		HttpUtils httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("UA", "Android");
		params.addBodyParameter("Version", Info.APIVERSION);
		params.addBodyParameter("UserAccount", userName);
		params.addBodyParameter("Password", pwd);
		params.addBodyParameter("VerificationKey", VerificationKey);
		LogUtil.e("==", userName + "==" + pwd);
		FileLogUtils.write("AutoLogin:" + Constant.getLoginUrl());
		httpUtils.send(HttpRequest.HttpMethod.POST, Constant.getLoginUrl(), params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {

				LogUtil.i(TAG, "Login response " + responseInfo.result);
				try {
					JSONObject responseJson;
					responseJson = new JSONObject(responseInfo.result);

					if (responseJson.has("Result")) {

						String result = responseJson.getString("Result");
						if (result.equals("true")) {
							if (responseJson.has("Token")) {
								String token = responseJson.getString("Token");
								Gson gson = new Gson();
								TestGroupLoginBean testGroupLoginBean = gson.fromJson(responseInfo.result, TestGroupLoginBean.class);
								String userid = testGroupLoginBean.getUserID();
								String userName = testGroupLoginBean.getUserName();
								int userType = testGroupLoginBean.getUserType();
								String userAccount = testGroupLoginBean.getUserAccount();
								if(null!=userid) {
									((TalkApplication) getApplication()).setUserID(Integer.parseInt(userid));
								}
								Intent intent = new Intent(MainActivity.this, CourseInfoActivity.class);
								intent.putExtra("token", token);
								intent.putExtra("UserID", userid);
								intent.putExtra("UserType", userType);
								intent.putExtra("UserName", userName);
								intent.putExtra("AgencyID", LOGIN_MECHANISM_ID);
								intent.putExtra("UserAccount", userAccount);
								startActivity(intent);
								finish();
							}
						} else {
							ThreadUtils.runOnMainThread(new Runnable() {
								@Override
								public void run() {
									ToastUtils.showToast(MainActivity.this,getResources().getString(R.string.login_failed_and_check_info));
									goApp(1000);
								}
							});
						}
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}

			@Override
			public void onFailure(HttpException e, final String s) {
				ThreadUtils.runOnMainThread(new Runnable() {
					@Override
					public void run() {
						LogUtil.e("loginfailed", s);
						ToastUtils.showToast(MainActivity.this, s);
						goApp(0);
					}
				});
			}
		});
	}

	private void showUpdateDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setCancelable(false);
		builder.setIcon(android.R.drawable.ic_dialog_info);
		// 1.设置title
		builder.setTitle("版本更新提醒");
		// 2.设置内容
		if(null!=replaceUpdateContent){
			builder.setMessage(replaceUpdateContent);
		}else{
			builder.setMessage("检测到最新版本，请及时更新！");
		}

		// 3.设置按钮
		builder.setNegativeButton("稍后再说", new DialogInterface.OnClickListener() {
			@Override
			public void onClick( DialogInterface dialog, int which) {
				// 进入主页
				load2Home();
			}
		});
		builder.setPositiveButton("立刻更新", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				ThreadUtils.runOnMainThread(new Runnable() {
					@Override
					public void run() {
						updateApk();
					}
				});

			}
		});
		builder.show();
	}

	protected void updateApk() {
		// 显示更新进度dialog
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		mProgressDialog.setCancelable(false);
		mProgressDialog.show();

		if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
				!= PackageManager.PERMISSION_GRANTED) {
			// Camera permission has not been granted.
			requestWritePermission();
		} else {
			// 下载
			new Thread(new DownloadApkTask(mProgressDialog)).start();
		}
	}

	private void requestWritePermission() {
		if (ActivityCompat.shouldShowRequestPermissionRationale(this,
				Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
			ActivityCompat.requestPermissions(MainActivity.this,
					new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
					REQUEST_WRITE);
		} else {
			// Camera permission has not been granted yet. Request it directly.
			ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
					REQUEST_WRITE);
		}
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

		if(requestCode==REQUEST_WRITE){
			LogUtil.i(TAG, "Received response for write permission request.");

			//获取到读权限
			if(grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
				new Thread(new DownloadApkTask(mProgressDialog)).start();
			}
		}
	}

	private class DownloadApkTask implements Runnable {
		private ProgressDialog dialog;

		public DownloadApkTask(ProgressDialog dialog) {
			this.dialog = dialog;
		}

		@Override
		public void run() {

			URL url = null;

			try {
				url = new URL(mUrl);

				HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
				urlConnection.setConnectTimeout(5000);
				urlConnection.setReadTimeout(5000);
				if(200 == urlConnection.getResponseCode()) {

					if(android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED)){
						LogUtil.i(TAG,"可以使用内存");
						apkFile = new File(
								Environment.getExternalStorageDirectory(),

								System.currentTimeMillis() + ".apk");
					}else{
						LogUtil.i(TAG,"不可以可以使用内存");
						apkFile = new File(
								Environment.getDataDirectory().getAbsolutePath(),

								System.currentTimeMillis() + ".apk");
					}

					//得到输入流
					is = urlConnection.getInputStream();

					int contentLength = urlConnection.getContentLength();

					dialog.setMax((int) contentLength);
					// 写到本地
					os = new FileOutputStream(apkFile);

					byte[] buffer = new byte[1024];

					int progress = 0;
					int len = -1;
					while ((len = is.read(buffer)) != -1) {

						os.write(buffer, 0, len);
						os.flush();

						progress += len;

						// 进度的
						dialog.setProgress(progress);// 设置进度
					}
					installApk(apkFile);
				}else{
					// 下载失败
					load2Home();
					Message msg = Message.obtain();
					msg.what = TYPE_SHOW_ERROR;
					msg.obj = "Error:101006";
					mHandler.sendMessage(msg);

				}
			}catch (IOException e) {
				Message msg = Message.obtain();
				msg.what = TYPE_SHOW_ERROR;
				msg.obj = "Error:101007";
				mHandler.sendMessage(msg);
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					is = null;
				}

				if (os != null) {
					try {
						os.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
					os = null;
				}
			}
			dialog.dismiss();
		}
	}

	private void load2Home() {
		LogUtil.i(TAG,"22222222");
		Intent intent = new Intent(this, LoginActivity.class);
		startActivity(intent);

		finish();
	}

	public void installApk(File file) {
		// 调用系统的安装程序

		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		//intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivityForResult(intent, REQUEST_INSTALL_CODE);
		//startActivity(intent);

	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// int requestCode: startActivityForResult 中的requestCode
		// int resultCode: 对应打开的activity响应的结果码,
		// Intent data

		if (requestCode == REQUEST_INSTALL_CODE) {
			// 请求安装返回的结果

			// 确定，取消
			switch (resultCode) {
				case Activity.RESULT_CANCELED:
					// 取消
					LogUtil.i(TAG, "取消安装");
					load2Home();
					break;
				case Activity.RESULT_OK:
					// 确定
					LogUtil.i(TAG, "确定安装");
					android.os.Process.killProcess(android.os.Process.myPid());//杀死自己进程的方法
					break;
				default:
					break;
			}
		}

	}

	private void initData() {
		// 1.获得包管理器
		PackageManager pm = getPackageManager();
		PackageInfo packageInfo;
		try {
			// 2.获得清单文件对象
			packageInfo = pm.getPackageInfo(getPackageName(), 0);
			versionName = packageInfo.versionName;
			FileLogUtils.write("Version:" + versionName);
		} catch (PackageManager.NameNotFoundException e) {
			e.printStackTrace();

		}
	}
	/*
	 * @Override public void onConfigurationChanged(Configuration newConfig) {
	 * super.onConfigurationChanged(newConfig); }
	 */

	private void goApp(long delayInMillis) {

		goApp(delayInMillis, LoginActivity.class);
	}

	private void goApp(long delayInMillis, final Class clazz) {

		new Handler().postDelayed(new Runnable() {
			@Override
			public void run() {
				Intent toMain = new Intent(MainActivity.this, clazz);
				startActivity(toMain);
				finish();
			}
		}, delayInMillis);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		InfoAccessImpl.getInstance(this).unbindAuthService();
		EventBus.getDefault().unregister(this);
	}
}